<?php

// deal with user details

function validate_details_form($doing_admin, $adding_new) {

  $form_ok = TRUE;
  $error_msgs[] = 'Some of your details were invalid. Please check the following:';
  if ($doing_admin) {
    if (empty($_POST['login'])) {
      $error_msgs[] = 'You must specify a login.';
    }
  }
  if ($adding_new) {
    if (empty($_POST['password1'])) {
      $error_msgs[] = 'You must specify a password.';
    }
  } 

  // Check for a new password and match against the confirmed password.
  if (! empty($_POST['password1'])) {
    if (eregi ('^[[:alnum:]]{4,20}$', stripslashes(trim($_POST['password1'])))) {
      if ($_POST['password1'] != $_POST['password2']) {
        $form_ok = FALSE;
        $error_msgs[] = 'Your password did not match the confirmed password.';
      }
    } else {
      $form_ok = FALSE;
      $error_msgs[] = 'Your new password is not valid.';
    }
  }
  // must specify first name, last name
  if (empty($_POST['fname'])) {
    $error_msgs[] = 'You must specify your first name.';
  }
  if (empty($_POST['lname'])) {
    $error_msgs[] = 'You must specify your last name.';
  }

  // email address must be valid if it exists
  if (! empty($_POST['email'])) {
    if (! eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['email'])))) {
      $error_msgs[] = 'Please give a valid email address.';
    }
  } else { // it is empty, so set email allowed to false
    $_POST['email_allowed'] = 0;
    $_POST['admin_email_ok'] = 0;
  }

  return $error_msgs;
}

function get_initial_value($row, $col_name, $field_name) {
  if (isset($_POST[$field_name])) {
    return stripslashes($_POST[$field_name]);
  } else {
    return stripslashes($row[$col_name]);
  }
}

function get_initial_is($row, $col_name, $field_name) {
  return ( (isset($_POST[$field_name]) && $_POST[$field_name]) || $row[$col_name]);
}

function update_user_details($user_id, $doing_admin, $adding_new) {
  if (!$adding_new) {
    really_update_user_details($user_id, $doing_admin);
    return $user_id;
  } else  {
    return add_user_details();
  }
} 
function really_update_user_details($user_id, $doing_admin) {
  // Make the query.
  $query = "UPDATE user_details SET ";
  $query .= add_update_field('first_name', 'fname');
  $query .= ", " . add_update_field('last_name', 'lname');
  $query .= ", " . add_update_field('title', 'title');
  $query .= ", " . add_update_field('address1', 'address1');
  $query .= ", " . add_update_field('address2', 'address2');
  $query .= ", " . add_update_field('address3', 'address3');
  $query .= ", " . add_update_field('address4', 'address4');
  $query .= ", " . add_update_field('post_code', 'postcode');
  $query .= ", " . add_update_field('home_phone', 'hphone');
  $query .= ", " . add_update_field('work_phone', 'wphone');
  $query .= ", " . add_update_field('mobile_phone', 'mphone');
  $query .= ", " . add_update_field('email', 'email');
  $query .= ", " . add_update_field('email_allowed', 'email_allowed');
  $query .= ", " . add_update_field('admin_email_ok', 'admin_email_ok');
  if ($doing_admin) {
    $query .= ", " . add_update_field('election_year', 'election_year');
    $query .= ", " . add_update_field('stop_year', 'stop_year');
    $query .= ", " . add_update_field('is_current', 'is_current');
    $query .= ", " . add_update_field('is_committee', 'is_committee');
  }
  $query .= " WHERE user_id=$user_id";

  $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());

  if (! empty($_POST['password1'])) { // we are changing the password
    $p =  escape_data($_POST['password1']);
    $query = "UPDATE users SET pass=SHA('$p') WHERE user_id=$user_id";	
    $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
  }
  if ($doing_admin) {
      $query = "UPDATE users SET ";
      $query .= add_update_field('login', 'login');
      $query .= ", " . add_update_field('level', 'level');
      $query .= " WHERE user_id=$user_id";
      $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
  }

  if ( $doing_admin) {
    $query = "UPDATE users SET last_admin_change = NOW() WHERE user_id=$user_id";
  } else {
    $query = "UPDATE users SET last_user_change = NOW() WHERE user_id=$user_id";
  }
  $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());


  // deal with the blurb
  $p =  escape_data($_POST['blurb']);
  $query = "UPDATE user_blurb SET blurb='$p' WHERE user_id=$user_id";	
  $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());


  // deal with undergraduate subjects
  update_user_things( 'user_subject', 1, 'ugrad', $user_id);

  // deal with postgraduate subjects
  update_user_things( 'user_subject', 2, 'pgrad', $user_id);

  // deal with current interests
  update_user_things( 'user_interest', 1, 'interest', $user_id);

 // deal with advice
  update_user_things( 'user_advice', 1, 'advice', $user_id);

 
}

function update_user_things($table, $level, $optionParam, $user_id) {
    if ( isset($_POST[$optionParam]) ) {
        $vals=$_POST[$optionParam];
        // remove the old values
        $query = "DELETE FROM $table WHERE user_id=$user_id and level=$level";
        $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
        
        // add the new values
        $first = TRUE;
        $query = '';
        foreach ($vals as $val) {
            if ($val != 0) {
                if ($first) {
                    $query = "INSERT INTO $table VALUES ";
                }
                else
                {
                    $query .= ", ";
                }
                $query .= "($user_id, $val, $level)";
                $first = FALSE;
            }
        }
        if ( '' != $query) {
            $result = mysql_query ($query) or 
                trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
        }
    }
}

function add_update_field($column, $field) {
  $val = escape_data($_POST[$field]);
  $ans = " $column='$val'";
  return $ans;
}

function fetch_all_thing_results($thing)
{
  $query = "SELECT {$thing}_id, {$thing} FROM all_{$thing}s ORDER BY {$thing}";
  $result = mysql_query($query)  or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
  return $result;
}

function add_user_details() {
  $p =  escape_data($_POST['password1']);
  $l1 = escape_data($_POST['login']);
  $l2 = escape_data($_POST['level']);
  $query = "INSERT INTO users (login, pass, level) VALUES ('$l1', SHA('$p'), '$l2')";
  $result = mysql_query($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
  // now get the user_id
  $user_id = mysql_insert_id();
  // add an entry into the user_details table
  $l1 = escape_data($_POST['fname']);
  $l2 = escape_data($_POST['lname']);
  $l3 = escape_data($_POST['address1']);
  $query = "INSERT INTO user_details (user_id, first_name, last_name, address1) VALUES ($user_id, '$l1', '$l2', '$l3')";
  $result = mysql_query($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
  // and add an entry into the blurb table
  $query = "INSERT INTO user_blurb (user_id) VALUES ($user_id)";
  $result = mysql_query($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
  // we can now update the rest of the things as usual
  really_update_user_details($user_id, TRUE);
  return $user_id;
}

// either to a text input field or straight, depending
function echo_user_details($use_input_field, $field_name, $field_size,
                           $user_details, $col_name ) {
    if ($use_input_field) {
        echo "<input type=\"text\" name=\"";
        echo $field_name;
        echo "\" size=\"";
        echo $field_size;
        echo "\" maxlength=\"";
        echo $field_size;
        echo "\" value=\"";
    }
    echo get_initial_value($user_details, $col_name, $field_name);
    if ($use_input_field) {
        echo "\"/>";
    } 
}

?>

